package com.yq.topCode;

/**
 * @ClassName Solution21MergeTwoLists
 * @Description TODO
 * @Author yaoqiang
 * @Date 2022/8/8 9:35
 * @Version 1.0
 */
public class Solution21MergeTwoLists {
    public static void main(String[] args) {
        Solution707MyLinedList obj=new Solution707MyLinedList();
        int[] arr1=new int[]{1,2,4};
        obj.addbyints(arr1);
        Solution707MyLinedList obj2=new Solution707MyLinedList();
        int[] l2=new int[]{1,3,4};
        obj2.addbyints(l2);
//        ListNode ret= mergeTwoLists(obj.head,obj2.head);
        ListNode ret2= mergeTwoLists2(obj.head,obj2.head);
        System.out.println(ret2);
    }
    public static ListNode mergeTwoLists(ListNode l1,ListNode l2){
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
    public static ListNode mergeTwoLists2(ListNode list1,ListNode list2){
        ListNode prehead=new ListNode(-1);
        ListNode pre=prehead;
        while (list1!=null && list2!=null){
            if(list1.val<=list2.val){
                pre.next=list1;
                list1= list1.next;
            }else{
                pre.next=list2;
                list2=list2.next;
            }
            pre=pre.next;
        }
        pre.next=list1==null?list2:list1;
        return prehead.next;
    }
}
